<template>
  <el-dialog
    v-model="dialogVisible"
    title="执行详情"
    width="90%"
    :close-on-click-modal="false"
  >
    <div v-if="execution" class="execution-detail">
      <!-- 执行基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <span>执行信息</span>
            <el-tag :type="getStatusType(execution.status)">
              {{ getStatusText(execution.status) }}
            </el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>执行名称：</label>
              <span>{{ execution.execution_name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>脚本名称：</label>
              <span>{{ execution.script_name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>执行人：</label>
              <span>{{ execution.executor_name }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{ formatTime(execution.start_time) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>结束时间：</label>
              <span>{{ formatTime(execution.end_time) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>执行时长：</label>
              <span>{{ formatDuration(execution.duration) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ execution.total_count || 0 }}</div>
              <div class="stat-label">总任务数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number success">{{ execution.success_count || 0 }}</div>
              <div class="stat-label">成功数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number danger">{{ execution.failed_count || 0 }}</div>
              <div class="stat-label">失败数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ getSuccessRate() }}%</div>
              <div class="stat-label">成功率</div>
            </div>
          </el-col>
        </el-row>
        
        <div v-if="execution.error_message" class="error-message">
          <label>错误信息：</label>
          <div class="error-text">{{ execution.error_message }}</div>
        </div>
      </el-card>

      <!-- 任务执行结果 -->
      <el-card class="tasks-card">
        <template #header>
          <span>任务执行结果</span>
        </template>
        
        <el-collapse v-model="activeTasks" accordion>
          <el-collapse-item
            v-for="(task, index) in taskResults"
            :key="task.id"
            :title="getTaskTitle(task, index)"
            :name="task.id"
          >
            <template #title>
              <div class="task-header">
                <span class="task-name">{{ task.task_name }}</span>
                <el-tag
                  :type="getStatusType(task.status)"
                  size="small"
                  style="margin-left: 8px;"
                >
                  {{ getStatusText(task.status) }}
                </el-tag>
                <span class="task-duration">{{ formatDuration(task.duration) }}</span>
              </div>
            </template>
            
            <div class="task-detail">
              <!-- 任务信息 -->
              <div class="task-info">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <div class="info-item">
                      <label>开始时间：</label>
                      <span>{{ formatTime(task.start_time) }}</span>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="info-item">
                      <label>结束时间：</label>
                      <span>{{ formatTime(task.end_time) }}</span>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="info-item">
                      <label>步骤数：</label>
                      <span>{{ task.step_count }}</span>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="info-item">
                      <label>成功/失败：</label>
                      <span>{{ task.success_steps }}/{{ task.failed_steps }}</span>
                    </div>
                  </el-col>
                </el-row>
                
                <div v-if="task.error_message" class="task-error">
                  <label>错误信息：</label>
                  <div class="error-text">{{ task.error_message }}</div>
                </div>
              </div>

              <!-- 步骤执行结果 -->
              <div v-if="task.step_results && task.step_results.length" class="steps-section">
                <h4>步骤执行详情</h4>
                <el-table :data="task.step_results" size="small" border>
                  <el-table-column prop="step_index" label="步骤" width="60" />
                  <el-table-column prop="step_type" label="类型" width="120" />
                  <el-table-column prop="step_content" label="内容" show-overflow-tooltip />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getStatusType(row.status)" size="small">
                        {{ getStatusText(row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="duration" label="耗时" width="100">
                    <template #default="{ row }">
                      {{ formatDuration(row.duration) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button
                        v-if="row.screenshot_url"
                        size="small"
                        @click="viewScreenshot(row.screenshot_url)"
                      >
                        查看截图
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 任务截图 -->
              <div v-if="task.screenshot_urls && task.screenshot_urls.length" class="screenshots-section">
                <h4>任务截图</h4>
                <div class="screenshots-grid">
                  <div
                    v-for="(url, idx) in task.screenshot_urls"
                    :key="idx"
                    class="screenshot-item"
                    @click="viewScreenshot(url)"
                  >
                    <img :src="url" :alt="`截图 ${idx + 1}`" />
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button v-if="execution.status === 'running'" type="warning" @click="stopExecution">
          <el-icon><VideoPause /></el-icon>
          停止执行
        </el-button>
        <el-button type="primary" @click="downloadReport">
          <el-icon><Download /></el-icon>
          下载报告
        </el-button>
      </div>
    </template>

    <!-- 截图查看器 -->
    <ScreenshotViewer
      v-model:visible="screenshotViewerVisible"
      :image-url="currentScreenshotUrl"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPause, Download } from '@element-plus/icons-vue'
import { getUiAutomationExecution, stopUiAutomationExecution } from '../../api/uiAutomation'
import ScreenshotViewer from './ScreenshotViewer.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  execution: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible'])

// 响应式数据
const activeTasks = ref([])
const taskResults = ref([])
const screenshotViewerVisible = ref(false)
const currentScreenshotUrl = ref('')

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听器
watch(() => props.visible, (visible) => {
  if (visible && props.execution) {
    loadExecutionDetail()
  }
})

// 方法
const loadExecutionDetail = async () => {
  try {
    const response = await getUiAutomationExecution(props.execution.id)
    if (response.success && response.data.task_results) {
      taskResults.value = response.data.task_results
    }
  } catch (error) {
    console.error('加载执行详情失败:', error)
    ElMessage.error('加载执行详情失败')
  }
}

const handleClose = () => {
  dialogVisible.value = false
  activeTasks.value = []
  taskResults.value = []
}

const stopExecution = async () => {
  try {
    const response = await stopUiAutomationExecution(props.execution.id)
    if (response.success) {
      ElMessage.success('执行已停止')
      // 刷新执行状态
      loadExecutionDetail()
    }
  } catch (error) {
    console.error('停止执行失败:', error)
    ElMessage.error('停止执行失败')
  }
}

const downloadReport = () => {
  // TODO: 实现报告下载功能
  ElMessage.info('报告下载功能开发中')
}

const viewScreenshot = (url) => {
  currentScreenshotUrl.value = url
  screenshotViewerVisible.value = true
}

const getTaskTitle = (task, index) => {
  return `${index + 1}. ${task.task_name}`
}

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'running': 'warning',
    'success': 'success',
    'failed': 'danger',
    'cancelled': ''
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待执行',
    'running': '执行中',
    'success': '成功',
    'failed': '失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

const formatDuration = (duration) => {
  if (!duration) return '-'
  if (duration < 1000) return `${duration}ms`
  if (duration < 60000) return `${Math.round(duration / 1000)}s`
  const minutes = Math.floor(duration / 60000)
  const seconds = Math.floor((duration % 60000) / 1000)
  return `${minutes}m${seconds}s`
}

const getSuccessRate = () => {
  if (!props.execution) return 0
  const total = (props.execution.success_count || 0) + (props.execution.failed_count || 0)
  if (total === 0) return 0
  return Math.round(((props.execution.success_count || 0) / total) * 100)
}
</script>

<style lang="scss" scoped>
.execution-detail {
  .info-card,
  .tasks-card {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  
  .info-item {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    label {
      font-weight: 600;
      color: #303133;
      margin-right: 8px;
    }
    
    span {
      color: #606266;
    }
  }
  
  .stat-item {
    text-align: center;
    
    .stat-number {
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      line-height: 1;
      margin-bottom: 4px;
      
      &.success {
        color: #67c23a;
      }
      
      &.danger {
        color: #f56c6c;
      }
    }
    
    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
  
  .error-message,
  .task-error {
    margin-top: 16px;
    
    label {
      font-weight: 600;
      color: #f56c6c;
      margin-right: 8px;
    }
    
    .error-text {
      margin-top: 4px;
      padding: 8px;
      background-color: #fef0f0;
      border: 1px solid #fbc4c4;
      border-radius: 4px;
      color: #f56c6c;
      font-size: 12px;
      line-height: 1.4;
    }
  }
  
  .task-header {
    display: flex;
    align-items: center;
    width: 100%;
    
    .task-name {
      flex: 1;
      font-weight: 600;
    }
    
    .task-duration {
      margin-left: 8px;
      font-size: 12px;
      color: #666;
    }
  }
  
  .task-detail {
    .task-info {
      margin-bottom: 20px;
    }
    
    .steps-section {
      margin-bottom: 20px;
      
      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .screenshots-section {
      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
      
      .screenshots-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 12px;
        
        .screenshot-item {
          border: 1px solid #e4e7ed;
          border-radius: 4px;
          overflow: hidden;
          cursor: pointer;
          transition: border-color 0.3s;
          
          &:hover {
            border-color: #409eff;
          }
          
          img {
            width: 100%;
            height: 100px;
            object-fit: cover;
            display: block;
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 8px;
  }
}

:deep(.el-collapse) {
  .el-collapse-item__header {
    padding-left: 0;
    padding-right: 0;
  }
  
  .el-collapse-item__content {
    padding-bottom: 0;
  }
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;
  }
}
</style>